import React from 'react';
import { Card, Space, Button, Form, Input, Select, DatePicker, Table, Tag, message } from 'antd';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;

// 模拟服务类型字典
const serviceTypeDict = [
  { value: 'recharge', label: '充值' },
  { value: 'withdraw', label: '提现' },
  { value: 'consume', label: '消费' },
  { value: 'refund', label: '退款' },
  { value: 'settlement', label: '结算' },
];

// 生成模拟数据：账单明细
const mockDetailData = Array.from({ length: 58 }).map((_, i) => {
  const types = serviceTypeDict.map(d => d.value);
  const type = types[i % types.length];
  const states = [0, 1]; // 0/1
  const state = states[i % states.length];
  const amount = ((i + 3) * (i % 2 === 0 ? 6.2 : 9.1));
  return {
    orderNumber: `ORD-${String(3000 + i).padStart(5, '0')}`,
    userName: `user_${i}`,
    nickName: `昵称${i}`,
    price: amount,
    equipmentNo: `EQ-${String(i).padStart(4, '0')}`,
    state: state,
    type: type,
    createTime: dayjs().subtract(i, 'hour').format('YYYY-MM-DD HH:mm:ss'),
  };
});

export default function WalletDetail() {
  const [form] = Form.useForm();
  const [data, setData] = React.useState(mockDetailData);
  const [filtered, setFiltered] = React.useState(mockDetailData);

  const columns = [
    { title: '订单号', dataIndex: 'orderNumber', width: 160 },
    { title: '用户账号', dataIndex: 'userName', width: 160 },
    { title: '用户昵称', dataIndex: 'nickName', width: 140 },
    { title: '金额(¥)', dataIndex: 'price', width: 120, sorter: (a,b)=> a.price - b.price, render: (v)=> <span style={{ fontWeight: 600 }}>{Number(v).toFixed(2)}</span> },
    { title: '设备号', dataIndex: 'equipmentNo', width: 140 },
    { title: '状态', dataIndex: 'state', width: 100, render: (s)=> <Tag color={s === 1 ? 'green' : 'gold'}>{s === 1 ? '已完成' : '未完成'}</Tag> },
    { title: '类型', dataIndex: 'type', width: 120, render: (t)=> <Tag>{serviceTypeDict.find(d=> d.value===t)?.label || t}</Tag> },
    { title: '创建时间', dataIndex: 'createTime', width: 180, sorter: (a,b)=> dayjs(a.createTime).valueOf() - dayjs(b.createTime).valueOf() },
  ];

  const onSearch = () => {
    const values = form.getFieldsValue();
    const range = values.dateTime;
    const start = range && range.length === 2 ? range[0] : null;
    const end = range && range.length === 2 ? range[1] : null;
    const next = data.filter(row => {
      const matchUser = values.userName ? row.userName.includes(values.userName) : true;
      const matchNick = values.nickName ? row.nickName.includes(values.nickName) : true;
      const matchEq = values.equipmentNo ? row.equipmentNo.includes(values.equipmentNo) : true;
      const matchState = values.state !== undefined && values.state !== '' ? row.state === values.state : true;
      const matchType = values.serviceType ? row.type === values.serviceType : true;
      const t = dayjs(row.createTime);
      const matchDate = start && end ? (t.isAfter(start) && t.isBefore(end)) : true;
      return matchUser && matchNick && matchEq && matchState && matchType && matchDate;
    });
    setFiltered(next);
  };

  const onReset = () => {
    form.resetFields();
    setFiltered(data);
  };

  const exportCSV = () => {
    const headers = ['订单号','用户账号','用户昵称','金额(¥)','设备号','状态','类型','创建时间'];
    const lines = filtered.map(r => [
      r.orderNumber,
      r.userName,
      r.nickName,
      Number(r.price).toFixed(2),
      r.equipmentNo,
      r.state === 1 ? '已完成' : '未完成',
      serviceTypeDict.find(d=> d.value===r.type)?.label || r.type,
      r.createTime
    ].join(','));
    const csv = [headers.join(','), ...lines].join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `wallet_detail_${dayjs().format('YYYYMMDD_HHmmss')}.csv`;
    a.click();
    URL.revokeObjectURL(url);
    message.success('已导出（示例CSV）');
  };

  const totalAmount = React.useMemo(() => filtered.reduce((sum, r)=> sum + Number(r.price||0), 0), [filtered]);

  return (
    <div>
      {/* 顶部搜索与导出 */}
      <Card variant="borderless" styles={{ body: { paddingTop: 8, paddingBottom: 8 } }}>
        <Space direction="horizontal" style={{ width: '100%' }}>
          <Button onClick={exportCSV}>导出</Button>
          <Form form={form} layout="inline" style={{ flex: 1 }}>
            <Form.Item name="userName">
              <Input placeholder="用户账号" allowClear style={{ width: 160 }} />
            </Form.Item>
            <Form.Item name="nickName">
              <Input placeholder="用户昵称" allowClear style={{ width: 140 }} />
            </Form.Item>
            <Form.Item name="equipmentNo">
              <Input placeholder="设备号" allowClear style={{ width: 160 }} />
            </Form.Item>
            <Form.Item name="state">
              <Select allowClear placeholder="状态" style={{ width: 140 }} options={[
                { value: 0, label: '未完成' },
                { value: 1, label: '已完成' },
              ]} />
            </Form.Item>
            <Form.Item name="serviceType">
              <Select allowClear placeholder="流水类型" style={{ width: 140 }} options={serviceTypeDict} />
            </Form.Item>
            <Form.Item name="dateTime">
              <RangePicker showTime style={{ width: 360 }} />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button type="primary" onClick={onSearch}>查询</Button>
                <Button onClick={onReset}>重置</Button>
              </Space>
            </Form.Item>
          </Form>
        </Space>
      </Card>

      {/* 表格与汇总 */}
      <Card title="账单明细" variant="borderless" styles={{ body: { paddingTop: 8 } }}>
        <Table
          rowKey={(r)=> r.orderNumber}
          dataSource={filtered}
          columns={columns}
          pagination={{ pageSize: 10 }}
          scroll={{ x: 980 }}
          summary={() => (
            <Table.Summary.Row>
              <Table.Summary.Cell index={0} colSpan={3}>
                合计金额：
              </Table.Summary.Cell>
              <Table.Summary.Cell index={3}>
                <span style={{ fontWeight: 700 }}>¥{totalAmount.toFixed(2)}</span>
              </Table.Summary.Cell>
              <Table.Summary.Cell index={4} colSpan={4} />
            </Table.Summary.Row>
          )}
        />
      </Card>
    </div>
  );
}